/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.base.DanluBaseActivity;
import cn.com.dhc.danlu.activity.base.WebViewActivity;
import cn.com.dhc.danlu.activity.myself.AddressListActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.CountTimerButton;
import cn.com.dhc.danlu.widget.DLToolbar;
import cn.com.dhc.danlu.widget.EditTextLayout;
import cn.com.dhc.danlu.widget.RegisterEditText;
import cn.com.dhc.danlu.widget.RegisterEditText.onFocusCallBack;
import cn.com.dhc.danlu.widget.adapter.StoreTypeListViewAdapter;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.request.common.ValidatePhoneRequest;
import cn.com.hd.mall.web.webservices.entity.request.common.ValidationBizCodeRequest;
import cn.com.hd.mall.web.webservices.entity.request.regist.RegistRequest;
import cn.com.hd.mall.web.webservices.entity.response.common.UserAgreementResponse;
import cn.com.hd.mall.web.webservices.entity.response.common.ValidationBizResponse;
import cn.com.hd.mall.web.webservices.entity.response.regist.RegistResponse;
import cn.com.hd.mall.web.webservices.entity.response.regist.ShopTypeListResponse;
import cn.com.hd.mall.web.webservices.entity.response.regist.ShopTypeListResponse.ShopTypeCode;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;
import static cn.com.dhc.danlu.util.CommonConst.RegisterConst.REGISTER_RESPONSE_VAL_CODE_ERROR;

/**
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-01-19 16:32<br/>
 *
 * <p>
 * 注册画面
 * </p>
 */
public class RegisterActivity extends DanluBaseActivity implements OnClickListener {
    private DLToolbar dlToolbar;
    /**
     * 店铺类型 List
     */
    private ArrayList<String> list;
    /**
     * 店铺类型 codes
     */
    private ArrayList<ShopTypeCode> shopTypeCodes;
    /**
     * 店铺类型 所在布局
     */
    private RelativeLayout llytStoreType;
    /**
     * 店铺类型text
     */
    private TextView storeType;
    /**
     * 终端店区域
     */
    private RelativeLayout rllytStoreAdd;
    /**
     * 用户协议checkbox
     */
    private RelativeLayout rllyChkagree;
    /**
     * 终端店区域text
     */
    private TextView storeAdd;
    /**
     * 用户名 背景框
     */
    private RelativeLayout rllyUserName;
    /**
     * 用户名
     */
    private RegisterEditText userName;
    /**
     * 密码 背景框
     */
    private RelativeLayout rllyPassWord;
    /**
     * 手机号 背景框
     */
    private RelativeLayout rllyUserTel;
    /**
     * 手机号
     */
    private RegisterEditText userTel;
    /**
     * 手机验证码
     */
    private RegisterEditText verifyCode;
    /**
     * 手机验证码背景框
     */
    private RelativeLayout rllyVerifyCode;
    /**
     * 邀请码
     */
    private RegisterEditText invitationCode;
    /**
     * 邀请码背景框
     */
    private RelativeLayout rllyInvitationCode;
    /**
     * 终端店名背景框
     */
    private RelativeLayout rllyStoreName;
    /**
     * 终端店名
     */
    private RegisterEditText storeName;
    /**
     * 终端店详细地址 背景框
     */
    private RelativeLayout rllyStoreDetailAdd;
    /**
     * 终端店详细地址
     */
    private RegisterEditText storeDetailAdd;
    /**
     * 营业执照编号 背景框
     */
    private RelativeLayout rllyBusinessLicense;
    /**
     * 营业执照编号
     */
    private RegisterEditText businessLicense;
    /**
     * 用户协议
     */
    private TextView userProtocol;
    /**
     * 同意协议
     */
    private ImageView chkagree;

    private AlertDialog.Builder builder;
    /**
     * 终端店类型弹出框
     */
    private AlertDialog dialog;
    /**
     * 终端店类型请求模型
     */
    private BaseRequest form;
    /**
     * 同意用户协议的flag
     */
    private boolean agreeFlag = false;
    /**
     * 密码显示/隐藏 Flag
     */
    private boolean isChecked = false;
    /**
     * 下一步
     */
    private Button nextBtn;
    /**
     * 用户名
     */
    private String mUserName;
    /**
     * 密码
     */
    private String password;
    /**
     * 手机号
     */
    private String telnumber;
    /**
     * 验证码
     */
    private String verifycodeStr;
    /**
     * 邀请码
     */
    private String invitationcode;
    /**
     * 店铺类型
     */
    private String storetype;
    /**
     * 终端店区域
     */
    private String storeadd;
    /**
     * 详细地址
     */
    private String storedetailadd;
    /**
     * 店铺名称
     */
    private String storename;
    /**
     * 营业执照号
     */
    private String businesslicense;
    /**
     * 终端店所在省份code
     */
    private String terminalAreaProvinceCode;
    /**
     * 终端店所在市code
     */
    private String terminalAreaCityCode;
    /**
     * 终端店所在区code
     */
    private String terminalAreaDistrictCode;
    /**
     * 店铺类型code
     */
    private String storeTypeCode;

    private EditTextLayout mEtPwdInput;

    private CountTimerButton ctbTimer;
    private LinearLayout llVoice;
    private TextView tvGetVoiceCode;

    private String authCodeId;
    private String validePhone = "";
    /**
     * handler message标志
     */
    private int GOTO_CLICK = 100;

    Handler handler = new Handler () {
        @Override
        public void handleMessage (Message msg) {
            super.handleMessage (msg);
            if (msg.what == GOTO_CLICK) {
                // 调用button点击事件处理方法
                nextBtn.setClickable (true);
            }
        }
    };
    /**
     * 输入框焦点监听
     */
    private OnFocusChangeListener mOnFocusChangeListener = new OnFocusChangeListener () {
        @Override
        public void onFocusChange (View v, boolean hasFocus) {
            switch (v.getId ()) {
                case R.id.userName:
                    mUserName = userName.getText ().toString ().trim ();
                    userName.setonFocusChange (userName, hasFocus, new onFocusCallBack () {

                        @Override
                        public void onHasFocus () {
                            rllyUserName.setBackgroundColor (Color.WHITE);
                        }

                        @Override
                        public void onNoFocus () {
                            if (!CommonUtils.checkUserNameRule (mUserName)) {
                                rllyUserName.setBackgroundResource (R.drawable.register_edit_alert_bg);
                                ToastUtil.getInstance ().show (R.string.register_user_name);
                            } else {
                                rllyUserName.setBackgroundColor (Color.WHITE);
                            }
                        }
                    });
                    break;

                case R.id.et_input:
                    password = mEtPwdInput.getInputText ();
                    if (!hasFocus && !TextUtils.isEmpty (password)) {
                        if (!CommonUtils.checkPassWordRule (password)) {
                            rllyPassWord.setBackgroundResource (R.drawable.register_edit_alert_bg);
                            ToastUtil.getInstance ().show (R.string.register_pass_word_msg);
                        } else {
                            rllyPassWord.setBackgroundColor (Color.WHITE);
                        }
                    }
                    break;

                case R.id.userTel:
                    telnumber = userTel.getText ().toString ().trim ();
                    userTel.setonFocusChange (userTel, hasFocus, new onFocusCallBack () {
                        @Override
                        public void onNoFocus () {
                            if (CommonUtils.isStringBlank (telnumber) || !CommonUtils.isMobileNumber (telnumber)) {
                                rllyUserTel.setBackgroundResource (R.drawable.register_edit_alert_bg);
                                ToastUtil.getInstance ().show (R.string.register_tel_msg);
                            } else {
                                rllyUserTel.setBackgroundColor (Color.WHITE);
                            }
                        }

                        @Override
                        public void onHasFocus () {
                            rllyUserTel.setBackgroundColor (Color.WHITE);
                        }
                    });
                    break;

                case R.id.invitationCode:
                    invitationcode = invitationCode.getText ().toString ().trim ();
                    invitationCode.setonFocusChange (invitationCode, hasFocus, new onFocusCallBack () {
                        @Override
                        public void onNoFocus () {
                        }

                        @Override
                        public void onHasFocus () {
                            rllyInvitationCode.setBackgroundColor (Color.WHITE);
                        }
                    });
                    break;

                case R.id.businessLicense:
                    businesslicense = businessLicense.getText ().toString ().trim ();
                    businessLicense.setonFocusChange (businessLicense, hasFocus, new onFocusCallBack () {
                        @Override
                        public void onNoFocus () {
                            if (CommonUtils.isStringBlank (businesslicense)) {
                                rllyBusinessLicense.setBackgroundResource (R.drawable.register_edit_alert_bg);
                                ToastUtil.getInstance ().show (R.string.store_business_license_msg);
                            } else {
                                rllyBusinessLicense.setBackgroundColor (Color.WHITE);
                            }
                        }

                        @Override
                        public void onHasFocus () {
                            rllyBusinessLicense.setBackgroundColor (Color.WHITE);
                        }
                    });
                    break;

                case R.id.storeDetailAdd:
                    storedetailadd = storeDetailAdd.getText ().toString ().trim ();
                    storeDetailAdd.setonFocusChange (storeDetailAdd, hasFocus, new onFocusCallBack () {
                        @Override
                        public void onNoFocus () {
                            if (CommonUtils.isStringBlank (storedetailadd)) {
                                rllyStoreDetailAdd.setBackgroundResource (R.drawable.register_edit_alert_bg);
                                ToastUtil.getInstance ().show (R.string.register_store_detail_add_msg);
                            } else {
                                rllyStoreDetailAdd.setBackgroundColor (Color.WHITE);
                            }
                        }

                        @Override
                        public void onHasFocus () {
                            rllyStoreDetailAdd.setBackgroundColor (Color.WHITE);
                        }
                    });
                    break;

                case R.id.storeName:
                    storename = storeName.getText ().toString ().trim ();
                    storeName.setonFocusChange (storeName, hasFocus, new onFocusCallBack () {
                        @Override
                        public void onNoFocus () {
                            if (CommonUtils.isStringBlank (storename)) {
                                rllyStoreName.setBackgroundResource (R.drawable.register_edit_alert_bg);
                                ToastUtil.getInstance ().show (R.string.register_store_name_msg);
                            } else {
                                rllyStoreName.setBackgroundColor (Color.WHITE);
                            }
                        }

                        @Override
                        public void onHasFocus () {
                            rllyStoreName.setBackgroundColor (Color.WHITE);
                        }
                    });
                    break;
                case R.id.verifyCode:
                    if (hasFocus) {
                        rllyVerifyCode.setBackgroundColor (Color.WHITE);
                    }
                    break;
                default:
                    break;
            }
        }
    };
    private TextWatcher tw = new TextWatcher () {
        @Override
        public void beforeTextChanged (CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged (CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged (Editable s) {
            String inputStr = s.toString ().replace (" ", "");
            if (!TextUtils.isEmpty (inputStr) && inputStr.length () == 11) {
                if (ctbTimer.isEnabled ()) {
                    ctbTimer.setBackgroundResource (R.drawable.bg_register_timer_focusable);
                    ctbTimer.setTextColor (Color.WHITE);
                }
            } else {
                ctbTimer.setBackgroundResource (R.drawable.bg_register_timer_normal);
                ctbTimer.setTextColor (getResources ().getColor (R.color.color_444444));
            }
        }
    };

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_register);

        init ();
    }

    /**
     * 画面初始化
     */
    private void init () {
        dlToolbar = (DLToolbar) findViewById (R.id.dl_toolbar);
        rllyUserName = (RelativeLayout) findViewById (R.id.rllyUserName);
        userName = (RegisterEditText) findViewById (R.id.userName);
        rllyPassWord = (RelativeLayout) findViewById (R.id.rllyPassWord);
        rllyUserTel = (RelativeLayout) findViewById (R.id.rllyUserTel);
        userTel = (RegisterEditText) findViewById (R.id.userTel);
        rllyVerifyCode = (RelativeLayout) findViewById (R.id.rllyVerifyCode);
        verifyCode = (RegisterEditText) findViewById (R.id.verifyCode);
        invitationCode = (RegisterEditText) findViewById (R.id.invitationCode);
        rllyInvitationCode = (RelativeLayout) findViewById (R.id.rllyInvitationCode);
        rllyStoreName = (RelativeLayout) findViewById (R.id.rllyStoreName);
        storeName = (RegisterEditText) findViewById (R.id.storeName);
        rllyBusinessLicense = (RelativeLayout) findViewById (R.id.rllyBusinessLicense);
        businessLicense = (RegisterEditText) findViewById (R.id.businessLicense);
        llytStoreType = (RelativeLayout) findViewById (R.id.llytStoreType);
        storeType = (TextView) findViewById (R.id.storeType);
        rllytStoreAdd = (RelativeLayout) findViewById (R.id.rllytStoreAdd);
        storeAdd = (TextView) findViewById (R.id.storeAdd);
        rllyStoreDetailAdd = (RelativeLayout) findViewById (R.id.rllyStoreDetailAdd);
        storeDetailAdd = (RegisterEditText) findViewById (R.id.storeDetailAdd);
        chkagree = (ImageView) findViewById (R.id.chkagree);
        rllyChkagree = (RelativeLayout) findViewById (R.id.rllyChkagree);
        nextBtn = (Button) findViewById (R.id.nextBtn);
        userProtocol = (TextView) findViewById (R.id.userProtocol);
        mEtPwdInput = (EditTextLayout) findViewById (R.id.etl_input);

        ctbTimer = (CountTimerButton) findViewById (R.id.ctb_countdown);
        llVoice = (LinearLayout) findViewById (R.id.ll_voice);
        tvGetVoiceCode = (TextView) findViewById (R.id.tv_get_voicecode);

        form = new BaseRequest ();
        shopTypeCodes = new ArrayList<> ();
        list = new ArrayList<> ();
        chkagree.setVisibility (View.VISIBLE);
        nextBtn.setBackgroundResource (R.drawable.selector_button_press);
        nextBtn.setClickable (true);
        nextBtn.setOnClickListener (this);
        agreeFlag = true;
        setListener ();
    }

    /**
     * 设置监听
     */
    private void setListener () {
        rllytStoreAdd.setOnClickListener (this);
        rllyChkagree.setOnClickListener (this);
        llytStoreType.setOnClickListener (this);
        userProtocol.setOnClickListener (this);
        tvGetVoiceCode.setOnClickListener (this);
        userName.setOnFocusChangeListener (mOnFocusChangeListener);
        mEtPwdInput.setOnFocusChangeListener (mOnFocusChangeListener);
        userTel.setOnFocusChangeListener (mOnFocusChangeListener);
        verifyCode.setOnFocusChangeListener (mOnFocusChangeListener);
        invitationCode.setOnFocusChangeListener (mOnFocusChangeListener);
        businessLicense.setOnFocusChangeListener (mOnFocusChangeListener);
        storeName.setOnFocusChangeListener (mOnFocusChangeListener);
        storeDetailAdd.setOnFocusChangeListener (mOnFocusChangeListener);

        ctbTimer.setInnerClickListener (new CountTimerButton.OnInnerClickListener () {
            @Override
            public void onClick (View view) {
                String phone = userTel.getText ().toString ().trim ();
                if (TextUtils.isEmpty (phone)) {
                    ToastUtil.getInstance ().show ("请输入手机号");
                    rllyUserTel.setBackgroundResource (R.drawable.register_edit_alert_bg);
                    return;
                }
                if (!CommonUtils.isMobileNumber (userTel.getText ().toString ().trim ())) {
                    rllyUserTel.setBackgroundResource (R.drawable.register_edit_alert_bg);
                    ToastUtil.getInstance ().show (R.string.register_tel_msg);
                } else {
                    validatePhone (phone);
                }
            }

            @Override
            public void onCountFinish () {
                llVoice.setVisibility (View.VISIBLE);
            }
        });
        userTel.addTextChangedListener (tw);
        dlToolbar.setBackListener (new OnClickListener () {
            @Override
            public void onClick (View v) {
                // 隐藏键盘
                CommonUtils.hideSoftInputFromWindow (RegisterActivity.this, dlToolbar);
                finish ();
            }
        });
    }

    private void validatePhone (final String phone) {
        ValidatePhoneRequest req = new ValidatePhoneRequest ();
        req.setPhone (phone);
        req.setServerCode ("01");
        agent.getApi ().validatePhone (req)
                .compose (OperatorUtils.defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<BaseResponse> (this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess (BaseResponse baseResponse) {
                        rllyUserTel.setBackgroundColor (Color.WHITE);
                        llVoice.setVisibility (View.GONE);
                        sendVerifiCode (phone);
                    }

                    @Override
                    protected String parseBussinessException (String code) {
                        String str;
                        switch (code) {
                            case "2":
                                str = "手机号格式不对";
                                break;
                            case "3":
                                str = "手机号已注册";
                                break;
                            case "1":
                            default:
                                str = "失败";
                                break;
                        }
                        return str;
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        ToastUtil.getInstance ().show (displayMessage);
                    }
                });
    }

    @Override
    public void onClick (View v) {
        switch (v.getId ()) {
            case R.id.tv_get_voicecode:
                showGetVoiceCodeDialog ();
                break;
            // 获取区域列表
            case R.id.rllytStoreAdd:
                Intent intent = new Intent ();
                intent.putExtra ("REGISTER", "register");
                intent.setClass (RegisterActivity.this, AddressListActivity.class);
                startActivityForResult (intent, 100);
                break;

            // 用户协议
            case R.id.userProtocol:
                agent.getApi ()
                        .getAgreement (form)
                        .compose (OperatorUtils.<UserAgreementResponse>defaultSchedulers ())
                        .subscribe (new GeneralBusinessObserver<UserAgreementResponse> (this, R.string.loading_common_msg) {
                            @Override
                            protected void onSuccess (UserAgreementResponse model) {
                                WebViewActivity.startSelf (RegisterActivity.this, "用户协议", model.getUserAgreementUrl (), false);
                            }
                        });
                break;

            // 店铺类型
            case R.id.llytStoreType:
                llytStoreType.setClickable (false);
                if (list == null || list.isEmpty ()) {
                    //                    danluTaskProxy.getStoreTypeList(form, onStoreTypeListener);
                    agent.getApi ()
                            .getStoreTypeList (form)
                            .compose (OperatorUtils.<ShopTypeListResponse>defaultSchedulers ())
                            .subscribe (new GeneralBusinessObserver<ShopTypeListResponse> (this, R.string.loading_common_msg) {
                                @Override
                                protected void onSuccess (ShopTypeListResponse model) {
                                    if (null != model.getShopList ()) {
                                        list.clear ();
                                        shopTypeCodes = (ArrayList<ShopTypeCode>) model.getShopList ();
                                        for (int i = 0; i < model.getShopList ().size (); i++) {
                                            list.add (shopTypeCodes.get (i).getCodeValue ());
                                        }
                                        storeTypeDialog ();
                                    }
                                    llytStoreType.setClickable (true);
                                }

                                @Override
                                protected void onAlertTips (String displayMessage) {
                                    llytStoreType.setClickable (true);
                                    ToastUtil.getInstance ().show (TextUtils.isEmpty (displayMessage) ? "获取店铺类型失败" : displayMessage);
                                }
                            });
                } else {
                    storeTypeDialog ();
                }
                break;

            // 同意用户协议
            case R.id.rllyChkagree:
                if (agreeFlag) {
                    chkagree.setVisibility (View.GONE);
                    nextBtn.setBackgroundResource (R.drawable.background_btn_unenabled);
                    nextBtn.setClickable (false);
                    agreeFlag = false;
                } else {
                    chkagree.setVisibility (View.VISIBLE);
                    nextBtn.setBackgroundResource (R.drawable.selector_button_press);
                    nextBtn.setClickable (true);
                    nextBtn.setOnClickListener (this);
                    agreeFlag = true;
                }
                break;

            // 提交注册
            case R.id.nextBtn:
                // 发送handler消息之前，清空该消息
                handler.removeMessages (GOTO_CLICK);
                // 绑定一个msg，内容为接下来需要的button的ID，
                Message msg = Message.obtain ();
                msg.what = GOTO_CLICK;
                // 发送消息间隔0.5秒
                handler.sendMessageDelayed (msg, 500);
                nextBtn.setClickable (false);
                rllyUserName.setBackgroundColor (Color.WHITE);
                rllyPassWord.setBackgroundColor (Color.WHITE);
                rllyUserTel.setBackgroundColor (Color.WHITE);
                rllyStoreName.setBackgroundColor (Color.WHITE);
                rllyVerifyCode.setBackgroundColor (Color.WHITE);
                rllyInvitationCode.setBackgroundColor (Color.WHITE);
                rllyBusinessLicense.setBackgroundColor (Color.WHITE);
                rllyStoreDetailAdd.setBackgroundColor (Color.WHITE);
                mUserName = userName.getText ().toString ().trim ();
                password = mEtPwdInput.getInputText ();
                telnumber = userTel.getText ().toString ().trim ();
                verifycodeStr = verifyCode.getText ().toString ().trim ();
                invitationcode = invitationCode.getText ().toString ().trim ();
                businesslicense = businessLicense.getText ().toString ().trim ();
                storedetailadd = storeDetailAdd.getText ().toString ().trim ();
                storename = storeName.getText ().toString ().trim ();
                storetype = storeType.getText ().toString ().trim ();
                storeadd = storeAdd.getText ().toString ().trim ();
                if (!CommonUtils.checkUserNameRule (mUserName)) {
                    rllyUserName.setBackgroundResource (R.drawable.register_edit_alert_bg);
                    ToastUtil.getInstance ().show (R.string.register_user_name);
                    return;
                } else if (!CommonUtils.checkPassWordRule (password)) {
                    rllyUserName.setBackgroundColor (Color.WHITE);
                    rllyPassWord.setBackgroundResource (R.drawable.register_edit_alert_bg);
                    ToastUtil.getInstance ().show (R.string.register_pass_word_msg);
                    return;
                } else if (CommonUtils.isStringBlank (telnumber) || !CommonUtils.isMobileNumber (telnumber)) {
                    rllyPassWord.setBackgroundColor (Color.WHITE);
                    rllyUserTel.setBackgroundResource (R.drawable.register_edit_alert_bg);
                    ToastUtil.getInstance ().show (R.string.register_tel_msg);
                    return;
                } else if (CommonUtils.isStringBlank (storename)) {
                    rllyUserTel.setBackgroundColor (Color.WHITE);
                    rllyStoreName.setBackgroundResource (R.drawable.register_edit_alert_bg);
                    ToastUtil.getInstance ().show (R.string.register_store_name_msg);
                    return;
                } else if (CommonUtils.isStringBlank (businesslicense)) {
                    rllyStoreName.setBackgroundColor (Color.WHITE);
                    rllyBusinessLicense.setBackgroundResource (R.drawable.register_edit_alert_bg);
                    ToastUtil.getInstance ().show (R.string.store_business_license_msg);
                    return;
                } else if (CommonUtils.isStringBlank (storetype) || storetype.equals (getString (R.string.register_store_type))) {
                    rllyBusinessLicense.setBackgroundColor (Color.WHITE);
                    ToastUtil.getInstance ().show (R.string.register_store_type);
                    return;
                } else if (CommonUtils.isStringBlank (storeadd) || storeadd.equals (getString (R.string.register_store_add))) {
                    ToastUtil.getInstance ().show (R.string.register_store_add_msg);
                    return;
                } else if (CommonUtils.isStringBlank (storedetailadd)) {
                    rllyStoreDetailAdd.setBackgroundResource (R.drawable.register_edit_alert_bg);
                    ToastUtil.getInstance ().show (R.string.register_store_detail_add_msg);
                    return;
                } else if (TextUtils.isEmpty (authCodeId)) {
                    ToastUtil.getInstance ().show ("请输入验证码");
                    return;
                } else if (!telnumber.equals (validePhone)) {
                    ToastUtil.getInstance ().show (R.string.tips_wrong_identifying_code);
                    return;
                } else {
                    RegistRequest registRequest = new RegistRequest ();
                    if (!TextUtils.isEmpty (mUserName)) {
                        registRequest.setTerminalLoginName (mUserName);// 用户名
                    }
                    registRequest.setPassword (password);// 密码
                    registRequest.setRegisterTel (telnumber);// 手机号
                    registRequest.setVerificationCode (verifycodeStr);// 验证码
                    if (!TextUtils.isEmpty (invitationcode)) {
                        registRequest.setInvitationCode (invitationcode);// 邀请码
                    }

                    registRequest.setTerminalFullName (storename);// 店铺名
                    registRequest.setBusinessLicenseCode (businesslicense);// 营业执照
                    registRequest.setStoreTypeCode (storeTypeCode);// 店铺类型
                    registRequest.setTerminalAreaProvinceCode (terminalAreaProvinceCode);// 省
                    registRequest.setTerminalAreaCityCode (terminalAreaCityCode);// 市
                    registRequest.setTerminalAreaDistrictCode (terminalAreaDistrictCode);// 区
                    registRequest.setTerminalAddress (storedetailadd);// 详细地址
                    registRequest.setAuthCodeId (authCodeId);
                    registerSubmit (registRequest);  //注册网络请求
                }
                break;

            default:
                break;
        }

    }

    private void showGetVoiceCodeDialog () {
        final String phone = userTel.getText ().toString ().replace (" ", "");
        if (TextUtils.isEmpty (phone) || phone.length () != 11) {
            ToastUtil.getInstance ().show (R.string.consignee_tel_not_right);
            return;
        }

        String contentDes = getResources ().getString (R.string.should_receive_voicecall_des);
        Spannable span = CommonUtils.getSpan (this, contentDes, contentDes.indexOf ("("), contentDes.length (), 14, 12, R.color.color_ea4949);
        new ViewDialog.Builder (this)
                .setMessage (span)
                .setPositiveButton (R.string.free_answer, new DialogInterface.OnClickListener () {
                    @Override
                    public void onClick (DialogInterface dialog, int which) {
                        dialog.dismiss ();
                        requestToGetVoiceCall (phone);
                    }
                })
                .setNegativeButton (R.string.no_answer, new DialogInterface.OnClickListener () {
                    @Override
                    public void onClick (DialogInterface dialog, int which) {
                        dialog.dismiss ();
                    }
                }).create ().show ();
    }

    private void requestToGetVoiceCall (final String phone) {
        ValidationBizCodeRequest req = new ValidationBizCodeRequest ();
        req.setToken (agent.getToken ());
        req.setPhone (phone);
        req.setBizCode ("01");
        agent.getApi ().sendVoiceCode (req)
                .compose (OperatorUtils.<ValidationBizResponse>defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<ValidationBizResponse> (this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess (ValidationBizResponse validationBizResponse) {
                        authCodeId = validationBizResponse.getAuthCodeId ();
                        validePhone = phone;
                        llVoice.setVisibility (View.GONE);
                        startTimer ();
                        ToastUtil.getInstance ().show ("语音验证码已发送，请接听电话");
                    }

                    @Override
                    protected String parseBussinessException (String code) {
                        return code.equals ("2") ? getResources ().getString (R.string.tips_wrong_phone_num_format) : "语音验证码获取失败";
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        ToastUtil.getInstance ().show (displayMessage);
                    }
                });
    }

    /**
     * 提交注册
     *
     * @param registRequest
     *         注册请求体
     */
    private void registerSubmit (RegistRequest registRequest) {
        agent.getApi ()
                .registerSubmit (registRequest)
                .compose (OperatorUtils.<RegistResponse>defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<RegistResponse> (this, R.string.register_ing) {
                    @Override
                    protected void onSuccess (RegistResponse registResponse) {
                    }

                    @Override
                    public void onNext (RegistResponse model) {
                        String success = model.getSuccess ();
                        if (success.equals (CommonConst.RegisterConst.REGISTER_RESPONSE_SUCCESS_0)) {
                            ToastUtil.getInstance ().show (R.string.register_finish);
                            RegisterActivity.this.finish ();
                        } else if (success.equals (CommonConst.RegisterConst.REGISTER_RESPONSE_SUCCESS_1)) {
                            String wrongPos = model.getCheckResult ().getFirstValue (); // 错误位置
                            if (!TextUtils.isEmpty (wrongPos)) {
                                switch (wrongPos) {
                                    case CommonConst.RegisterConst.REGISTER_RESPONSE_T_NAME:  //用户名错误
                                        alertWrongMsg (rllyUserName, model);
                                        break;
                                    case CommonConst.RegisterConst.REGISTER_RESPONSE_PASS_WORD: //密码名错误
                                        alertWrongMsg (rllyPassWord, model);
                                        break;
                                    case CommonConst.RegisterConst.REGISTER_RESPONSE_TEL: //手机号错误
                                        alertWrongMsg (rllyUserTel, model);
                                        break;
                                    case CommonConst.RegisterConst.REGISTER_RESPONSE_VERFICATION_CODE: //验证码错误
                                        alertWrongMsg (rllyVerifyCode, model);
                                        break;
                                    case CommonConst.RegisterConst.REGISTER_RESPONSE_INVATI_CODE: //邀请码错误
                                        alertWrongMsg (rllyInvitationCode, model);
                                        break;
                                    case CommonConst.RegisterConst.REGISTER_RESPONSE_T_FULL_NAME: //终端店名称错误
                                        alertWrongMsg (rllyStoreName, model);
                                        break;
                                    case CommonConst.RegisterConst.REGISTER_RESPONSE_BUSS_CODE: //营业执照号错误
                                        alertWrongMsg (rllyBusinessLicense, model);
                                        break;
                                    case CommonConst.RegisterConst.REGISTER_RESPONSE_STORE_TYPE: //店铺类型错误
                                        if (model.getCheckResult ().getSecondValue () != null) {
                                            ToastUtil.getInstance ().show (model.getCheckResult ().getSecondValue ());
                                        }
                                        break;

                                    case CommonConst.RegisterConst.REGISTER_RESPONSE_PRO_CODE: //终端店区域省份错误
                                    case CommonConst.RegisterConst.REGISTER_RESPONSE_CITY_CODE: //终端店区域市错误
                                    case CommonConst.RegisterConst.REGISTER_RESPONSE_DIS_CODE: //终端店区域县错误
                                        if (model.getCheckResult ().getSecondValue () != null) {
                                            ToastUtil.getInstance ().show (model.getCheckResult ().getSecondValue ());
                                        }
                                        break;

                                    case CommonConst.RegisterConst.REGISTER_RESPONSE_T_ADDRESS: //详细地址错误
                                        alertWrongMsg (rllyStoreDetailAdd, model);
                                        break;
                                    case REGISTER_RESPONSE_VAL_CODE_ERROR:
                                        if (model.getCheckResult ().getSecondValue () != null) {
                                            ToastUtil.getInstance ().show (model.getCheckResult ().getSecondValue ());
                                        } else {
                                            ToastUtil.getInstance ().show ("验证码错误");
                                        }
                                    default:
                                        break;
                                }
                            }
                        }
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        ToastUtil.getInstance ().show (displayMessage);
                    }
                });
    }

    /**
     * 提示错误信息（位置及错误原因)
     *
     * @param view
     *         信息填写错误位置
     * @param model
     *         注册信息返回体
     */
    private void alertWrongMsg (View view, RegistResponse model) {
        view.setBackgroundResource (R.drawable.register_edit_alert_bg);
        if (model.getCheckResult ().getSecondValue () != null) {
            ToastUtil.getInstance ().show (model.getCheckResult ().getSecondValue ());
        }
    }
    private void startTimer(){
        ctbTimer.startTimer ();
        ctbTimer.setBackgroundResource (R.drawable.bg_register_timer_normal);
        ctbTimer.setTextColor (getResources ().getColor (R.color.color_444444));
    }
    /**
     * 发送验证码
     */
    private void sendVerifiCode (final String telNum) {
        ValidationBizCodeRequest req = new ValidationBizCodeRequest ();
        req.setBizCode ("01");
        req.setPhone (telNum);
        agent.getApi ()
                .sendMessageCode (req)
                .compose (OperatorUtils.<ValidationBizResponse>defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<ValidationBizResponse> (this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess (ValidationBizResponse validationBizResponse) {
                        authCodeId = validationBizResponse.getAuthCodeId ();
                        validePhone = telNum;
                        startTimer ();
                    }

                    @Override
                    protected String parseBussinessException (String code) {
                        return code.equals ("2") ? getResources ().getString (R.string.tips_wrong_phone_num_format) : "验证码获取失败";
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        ToastUtil.getInstance ().show (displayMessage);
                    }
                });
    }

    /**
     * 店铺类型 dialog
     */
    private void storeTypeDialog () {
        // 创建Builder
        if (builder == null) {
            builder = new AlertDialog.Builder (RegisterActivity.this);
        }

        // 设置自定义的View
        View view = LayoutInflater.from (this).inflate (R.layout.layout_store_type_list, null);
        final ListView listview = (ListView) view.findViewById (R.id.store_type_list);
        StoreTypeListViewAdapter adapters = new StoreTypeListViewAdapter (RegisterActivity.this, list);

        listview.setSelector (new ColorDrawable (Color.TRANSPARENT));
        listview.setAdapter (adapters);
        builder.setView (view);
        llytStoreType.setClickable (true);
        listview.setOnItemClickListener (new OnItemClickListener () {

            @Override
            public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
                storeType.setText (list.get (position));
                storeTypeCode = shopTypeCodes.get (position).getCodeId ();
                storeType.setTextColor (Color.BLACK);
                if (dialog != null) {
                    dialog.dismiss ();

                }
            }
        });

        // 创建对话框并显示
        if (dialog == null) {
            dialog = builder.create ();
        }
        dialog.show ();
    }

    @Override
    protected void onActivityResult (int requestCode, int resultCode, Intent data) {
        super.onActivityResult (requestCode, resultCode, data);
        switch (resultCode) {
            case 100:
                storeAdd.setText (data.getStringExtra ("ADDR"));
                storeAdd.setTextColor (Color.BLACK);
                terminalAreaProvinceCode = data.getStringExtra ("PCODE");
                terminalAreaCityCode = data.getStringExtra ("CCODE");
                terminalAreaDistrictCode = data.getStringExtra ("DCODE");
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy () {
        userTel.removeTextChangedListener (tw);
        super.onDestroy ();
    }
}